<template>
  <article class="media">
    <div class="media-content">
      <form @submit.prevent="onSubmit">
        <b-field>
          <b-input
            v-model.lazy="commentDTO.content"
            type="textarea"
            maxlength="400"
            placeholder="Add a comment..."
          ></b-input>
        </b-field>
        <nav class="level">
          <div class="level-left">
            <b-button
              type="is-primary"
              native-type="submit"
              class="level-item"
            >
              Comment
            </b-button>
          </div>
        </nav>
      </form>
    </div>
  </article>
</template>
<script>
import { addComment } from '../../../api/comment'

export default {
  name: 'CommentForm',
  data() {
    return {
      isLoading: false,
      commentDTO:{
        userId: 0,
        postId: 0,
        username: '',
        content: '',
      }
    }
  },
  props: ["postId"],
  methods: {
     onSubmit() {
      const user = JSON.parse(window.localStorage.getItem("user"));
      this.commentDTO.userId = user.id;
      this.commentDTO.postId = this.postId;
      this.commentDTO.username = user.username;
      console.log(this.commentDTO);
      addComment(this.commentDTO).then(res=>{
        const result = res.data;
        if(result.code == 0){
          this.$message({
            message: result.msg,
            type: "success",
          });
          this.commentDTO.content = '';
          //触发父组件事件告诉父组件已经进行评论
          this.$emit('loadComments',this.postId);
        }else{
          this.$message({
            message: result.msg,
            type: "error",
          });
        }
      })
    }
  }
}
</script>